package com.ouyunc.oauth2.service.impl;


import com.ouyunc.common.base.ResponseResult;
import com.ouyunc.oauth2.base.BaseUser;
import com.ouyunc.oauth2.feign.UserClient;
import com.ouyunc.oauth2.service.IUserDetailsService;
import com.ouyunc.service.dto.UserDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @Author fangzhenxun
 * @Description
 * @Date 2020/4/22 8:57
 **/
@Service
@Slf4j
public class IUserDetailsServiceImpl implements IUserDetailsService {

    /**
     * 用户客户端
     **/
    @Autowired
    private UserClient userClient;


    /**
     * @param username
     * @param extendMap
     * @return org.springframework.security.core.userdetails.UserDetails
     * @Author fangzhenxun
     * @Description 自定义方法，配置后走该方法，用户名密码模式，当然也可以从当前请求中获取
     * @todo  这里可以根据extendMap 中约定好的参数进行灵活请求处理
     * 实体类中别忘了使用 @UserDetail
     * @Date 2020/4/22 10:52
     **/
    @Override
    public UserDetails loadUserByUsername(String username, Map<String, Object> extendMap) throws UsernameNotFoundException {
        //pwd=12345689
        ResponseResult<UserDTO> loginResponse = userClient.getUserByUserName(username);
        BaseUser baseUser = new BaseUser();
        if (loginResponse.isSuccess()) {
            baseUser.setUserDetail(loginResponse.getData());
        }
        return baseUser;
    }

    /**
     * @return org.springframework.security.core.userdetails.UserDetails
     * @Author fangzhenxun
     * @Description 框架自带的方法, 授权码模式使用，自己的平台，对第三方暴露用户信息的登录认证逻辑
     * @Date 2020/4/22 9:03
     **/
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        ResponseResult<UserDTO> loginResponse = userClient.getUserByUserName(username);
        BaseUser baseUser = new BaseUser();
        if (loginResponse.isSuccess()) {
            baseUser.setUserDetail(loginResponse.getData());
        }
        return baseUser;
    }

}
